package com.qiguliuxing.dts.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.service.AdminDataAuthService;
import com.qiguliuxing.dts.admin.service.AdminGoodsService;
import com.qiguliuxing.dts.db.bean.GoodsAllinone;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.support.JacksonUtil;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsGoods;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/goods")
@Validated
@Api(tags = ApiAdminConsts.Goods.PARENT)
public class AdminGoodsController {
	private static final Logger logger = LoggerFactory.getLogger(AdminGoodsController.class);

	@Autowired
	private AdminGoodsService adminGoodsService;

	@Autowired
	private AdminDataAuthService adminDataAuthService;

	/**
	 * 查询商品
	 *
	 * @param goodsSn
	 * @param name
	 * @param page
	 * @param limit
	 * @param sort
	 * @param order
	 * @return
	 */
	@RequiresPermissions("admin:goods:list")
	@RequiresPermissionsDesc(menu = { "商品管理", "商品管理" }, button = "查询")
	@ApiOperation(value=ApiAdminConsts.Goods.LIST)
	@GetMapping("/list")
	@WebLog(description = ApiAdminConsts.Goods.LIST,excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "商品编号") String goodsSn,
					   @ApiParam(value = "商品名称") String name,
					   @ApiParam(value = "商品状态") @RequestParam(required = false) Boolean isOnSale,
					   @ApiParam(value = "商品分类") @RequestParam(required = false) Integer categoryId,
					   @ApiParam(value = "审批状态") @RequestParam(required = false) List<Byte> approveStatusArray,
					   @ApiParam(value = "页码",defaultValue = "1")  @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10")  @RequestParam(defaultValue = "10") Integer limit,
					   @ApiParam(value = "排序字段",defaultValue = "add_time")  @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @ApiParam(value = "排序规则",defaultValue = "desc")  @Order @RequestParam(defaultValue = "desc") String order) {
	    //需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
		List<Integer> brandIds = null;
		if (adminDataAuthService.isBrandManager()) {
			brandIds = adminDataAuthService.getBrandIds();
			logger.info("运营商管理角色操作，需控制数据权限，brandIds:{}",JSONObject.toJSONString(brandIds));

			if (brandIds == null || brandIds.size() == 0) {
				Map<String, Object> data = new HashMap<>(2);
				data.put("total", 0L);
				data.put("items", null);
				return ResponseUtils.ok(data);
			}
		}
		return adminGoodsService.list(goodsSn, name,isOnSale,categoryId, approveStatusArray, page, limit, sort, order, brandIds);
	}

	@ApiOperation(value="catAndBrand")
	@GetMapping("/catAndBrand")
	public Object catAndBrand() {
		return adminGoodsService.catAndBrand();
	}

	/**
	 * 编辑商品
	 *
	 * @param goodsAllinone
	 * @return
	 */
	@RequiresPermissions("admin:goods:update")
	@RequiresPermissionsDesc(menu = { "商品管理", "商品管理" }, button = "编辑")
	@ApiOperation(value=ApiAdminConsts.Goods.UPDATE)
	@PostMapping("/update")
	@WebLog(description = ApiAdminConsts.Goods.UPDATE, persistence = true)
	public Object update(@RequestBody GoodsAllinone goodsAllinone) {
		return adminGoodsService.update(goodsAllinone);
	}

	/**
	 * 删除商品
	 *
	 * @param goods
	 * @return
	 */
	@RequiresPermissions("admin:goods:delete")
	@RequiresPermissionsDesc(menu = { "商品管理", "商品管理" }, button = "删除")
	@ApiOperation(value=ApiAdminConsts.Goods.DELETE)
	@PostMapping("/delete")
	@WebLog(description = ApiAdminConsts.Goods.DELETE,persistence = true)
	public Object delete(@RequestBody DtsGoods goods) {
		return adminGoodsService.delete(goods);
	}

	/**
	 * 添加商品
	 *
	 * @param goodsAllinone
	 * @return
	 */
	@RequiresPermissions("admin:goods:create")
	@RequiresPermissionsDesc(menu = { "商品管理", "商品管理" }, button = "上架")
	@ApiOperation(value=ApiAdminConsts.Goods.CREATE)
	@PostMapping("/create")
	@WebLog(description = ApiAdminConsts.Goods.CREATE, persistence = true)
	public Object create(@RequestBody GoodsAllinone goodsAllinone) {
		return adminGoodsService.create(goodsAllinone);
	}

	/**
	 * 商品详情
	 *
	 * @param id
	 * @return
	 */
	@RequiresPermissions("admin:goods:read")
	@RequiresPermissionsDesc(menu = { "商品管理", "商品管理" }, button = "详情")
	@ApiOperation(value=ApiAdminConsts.Goods.READ)
	@GetMapping("/detail")
	@WebLog(description = ApiAdminConsts.Goods.READ)
	public Object detail(@ApiParam(value = "商品id") @NotNull Integer id) {
		return adminGoodsService.detail(id);
	}

	@RequiresPermissions("admin:goods:approveGoods")
	@RequiresPermissionsDesc(menu = { "商品管理", "商品管理" }, button = "商品审批")
	@ApiOperation(value=ApiAdminConsts.Goods.APPROVE)
	@PostMapping("/approveGoods")
	@WebLog(description = ApiAdminConsts.Goods.APPROVE, persistence = true)
	public Object approveGoods(@RequestBody String body) {
		Integer goodsId = JacksonUtil.parseInteger(body, "goodsId");
		Byte approveStatus = JacksonUtil.parseByte(body, "approveStatus");
		String approveMsg = JacksonUtil.parseString(body, "approveMsg");

		if (goodsId == null || approveStatus == null || approveMsg == null){
			return ResponseUtils.badArgument();
		}
		adminGoodsService.updateApproveStatus(goodsId,approveStatus,approveMsg);
		return ResponseUtils.ok();
	}

	/**
	 * 批量上架
	 * @param ids
	 * @return
	 */
	@RequiresPermissions("admin:goods:PutAway")
	@RequiresPermissionsDesc(menu = { "商品管理", "商品管理" }, button = "批量上架")
	@ApiOperation(value=ApiAdminConsts.Goods.CREATE)
	@PostMapping("/batchPutAway")
	@WebLog(description = ApiAdminConsts.Goods.CREATE, persistence = true)
	public Object batchPutAway(@ApiParam(value = "ids")  String ids){
		int i = adminGoodsService.batchPutAway(ids);
		if(i == 0){
			logger.error("商品管理->批量上架 错误:{}", "请勿重复上架!");
			return ResponseUtils.updatedDataFailed();
		}else if(i==2){
			return ResponseUtils.putWayDataFailed();
		}
		return ResponseUtils.ok();
	}

	/**
	 * 批量下架
	 *
	 * @param ids
	 * @return
	 */
	@RequiresPermissions("admin:goods:outAway")
	@RequiresPermissionsDesc(menu = { "商品管理", "商品管理" }, button = "批量下架")
	@ApiOperation(value=ApiAdminConsts.Goods.CREATE)
	@PostMapping("/batchOutAway")
	@WebLog(description = ApiAdminConsts.Goods.CREATE, persistence = true)
	public Object batchOutAway(@ApiParam(value = "ids") String ids){
		int flg=adminGoodsService.batchOutAway(ids);
		if (flg == 0) {
			return ResponseUtils.updatedDataFailed();
		}else if(flg==1){
			return ResponseUtils.ok();
		}if(flg==2){
			return ResponseUtils.fail(-1,"此商品已被活动关联，下架失败");
		}
		return ResponseUtils.ok();
	}
}
